#include <stdio.h>
#include "ServerSocket.h"
#include "File.h"
#include "FtpServicer.h"
#include <process.h>
#include "AccountManager.h"

using namespace std;


void FtpServicerThread(void *arg)
{
	FtpServicer *servicer = (FtpServicer*)arg;

	try
	{
		servicer->MainLoop();
	}
	catch(std::exception &e)
	{
		fprintf(stderr, "Error: %s\n", e.what());
	}

	delete servicer;
}

void FtpServer(const char* ftprootpath)
{
	ServerSocket server;
	AccountManager manager;
	FilePath root(ftprootpath, FilePath::NORESOLVE);

	printf("FTP root directory: \"%s\"\n", root.PathString().c_str());


	manager.AddAccount( Account("neimod", "neimodpass") );
	manager.AddAccount( Account("bjorn", "wowpass") );
	manager.AddAccount( Account("mark", "turingmachine") );
	manager.AddAccount( Account("raf", "ikillyou") );
	manager.AddAccount( Account("bart", "slashcare") );
	manager.AddAccount( Account("benji", "bengay") );


	server.Listen(21);

	for(;;)
	{
		try
		{
			FtpServicer *servicer = new FtpServicer( server.Accept(), manager, root);

			_beginthread(FtpServicerThread, 0, (void*)servicer);
		} 
		catch(std::exception &e)
		{
			fprintf(stderr, "Error: %s\n", e.what());
		}
	}
}

int main(int argc, char *argv[])
{
	const char *ftproot = ".";

	if (argc == 2)
	{
		ftproot = argv[1];
	}

	try
	{
		Socket::Startup();

		FtpServer(ftproot);

		Socket::Cleanup();
	}
	catch(std::exception &e)
	{
		fprintf(stderr, "Error: %s\n", e.what());
	}
	catch(...)
	{
		fprintf(stderr, "Error: unknown error\n");
	}

	return 0;
}



